import { defineStore } from 'pinia'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import apis from '@/plugins/http'
import { rolePerm } from '@/utils'
import Layout from '@/layouts/index.vue'
import ParentView from '@/layouts/components/ParentView/index.vue'
import InnerLink from '@/layouts/components/InnerLink/index.vue'


const allComponents = import.meta.glob('/src/views/**/**.vue')
export default defineStore('usePermissionStore', {
    state: () => {
        return {
            routes: [], addRoutes: [], defaultRoutes: [], topbarRouters: [], sidebarRouters: [],
        }
    }, actions: {
        generateRoutes() {
            return new Promise(resolve => {
                // 向后端请求路由数据
                apis.getRouters().then(res => {
                    const sdata = JSON.parse(JSON.stringify(res.data))
                    const rdata = JSON.parse(JSON.stringify(res.data))
                    const sidebarRoutes = filterAsyncRouter(sdata)
                    const rewriteRoutes = filterAsyncRouter(rdata, false, true)
                    const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
                    rewriteRoutes.push({path: '/:pathMatch(.*)*', redirect: '/404', hidden: true})
                    asyncRoutes.forEach(res => {
                        router.addRoute(res) // 动态添加可访问路由表
                    })
                    this.setRoutes(rewriteRoutes)
                    this.setSidebarRoutes(constantRoutes.concat(sidebarRoutes))
                    this.setDefaultRoutes(sidebarRoutes)
                    this.setTopbarRoutes(sidebarRoutes)
                    resolve(rewriteRoutes)
                })
            })
        }, setRoutes(routes) {
            this.addRoutes = routes
            this.routes = constantRoutes.concat(routes)
        }, setDefaultRoutes(routes) {
            this.defaultRoutes = constantRoutes.concat(routes)
        }, setTopbarRoutes(routes) {
            // 顶部导航菜单默认添加统计报表栏指向首页
            const index = [
                {
                    path: '/index', meta: {title: '统计报表', icon: 'dashboard'}
                }
            ]
            this.topbarRouters = routes.concat(index)
        }, setSidebarRoutes(routes) {
            this.sidebarRouters = routes
        }
    }
})

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
    return asyncRouterMap.filter(route => {
        if (type && route.children) {
            route.children = filterChildren(route.children)
        }
        if (route.component) {
            // Layout ParentView 组件特殊处理
            if (route.component === 'Layout') {
                route.component = Layout
            } else if (route.component === 'ParentView') {
                route.component = ParentView
            } else if (route.component === 'InnerLink') {
                route.component = InnerLink
            } else {
                const componentSrc = '/src/views/' + route.component + '.vue'
                // 如果未找到组件，则跳过该路由
                // if (component === undefined && (route.children === undefined || route.children?.length === 0)) return false
                route.component = allComponents[componentSrc]
            }
        }
        if (route.children != null && route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children, route, type)
        } else {
            delete route['children']
            delete route['redirect']
        }
        return true
    })
}

function filterChildren(childrenMap, lastRouter = false) {
    let children = []
    childrenMap.forEach(el => {
        if (el.children && el.children.length) {
            if (el.component === 'ParentView' && !lastRouter) {
                el.children.forEach(c => {
                    c.path = el.path + '/' + c.path
                    if (c.children && c.children.length) {
                        children = children.concat(filterChildren(c.children, c))
                        return
                    }
                    children.push(c)
                })
                return
            }
        }
        if (lastRouter) {
            el.path = lastRouter.path + '/' + el.path
        }
        children = children.concat(el)
    })
    return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
    const res = []
    routes.forEach(route => {
        if (route.permissions) {
            if (rolePerm.hasPermOr(route.permissions)) {
                res.push(route)
            }
        } else if (route.roles) {
            if (rolePerm.hasRoleOr(route.roles)) {
                res.push(route)
            }
        }
    })
    return res
}
